﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Architecture.Domain.TestModel.Samples;
using System.Net.Http;
using System.Net.Http.Headers;
using Architecture.CrossCutting.Common;
using Architecture.CrossCutting.Web.WebApi;

namespace Architecture.ServiceClient.Console
{

    class MessageHandler1 : DelegatingHandler
    {
        private int _count = 0;

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            _count++;
            request.Headers.Add("X-Custom-Header", _count.ToString());
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
            
            return response;
        }

    }

    public class WebapiClient
    {
        public async Task<List<Organisation>> GetOrganisations()
        {

            var messageHandler = CustomContext.Current.DependencyResolver.GetService<WebApiDiagnostic>();

            using (var client = HttpClientFactory.Create(messageHandler))
            //using (var client = HttpClientFactory.Create())
            {
                //client.BaseAddress = new Uri("http://localhost:27176/");
                client.BaseAddress = new Uri("http://localhost/WebApiServices/");

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/organisation");
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsAsync<List<Organisation>>();
                    //System.Console.WriteLine("{0}\t{1}", organisation[0].Name, organisation[0].Id);
                }
                else
                {
                    return new List<Organisation>();
                }
            }

        }
    }
}
